<?php

class ELMController extends commonController
{
    # 测试饿了么开发参数
    const SANDBOX_KEY = '7sU488MRSH';
    const SANDBOX_SECRET = '69be1d5920ed4738c23f0750f69f29a44a00360f';

    # 正式饿了么开发参数
    const KEY = 'Of3uIZzKD7';
    const SECRET = '4ef3a27e7d724a127b80ead9320f0ee210f485f3';

    # 饿了么 沙箱 + 正式 【暂弃用】
    const SANDBOX_URL = 'https://open-api-sandbox.shop.ele.me/api/v1/';
    const ELM_URL = 'https://open-api.shop.ele.me/api/v1/';


    # 饿了么 沙箱 + 正式 获取TOKEN 地址
    const ELM_SANDBOX_TOKEN_URL = 'https://open-api-sandbox.shop.ele.me/token';
    const ELM_TOKEN_URL = 'https://open-api.shop.ele.me/token';

    # 回调地址  必须为https（上线后）
    const JT_TEST_URL = 'http://zhaipei.shjieta.com.cn/';
    const ZP_URL = 'https://zhaipei.ganso.com.cn';
    # 正式环境：token：30天，refresh_token：35天。

    /**
     * 获取授权地址
     */
    public function getOauthUrlAction()
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $Rurl = (($webSite['debug']) ? self::JT_TEST_URL : self::ZP_URL) . '?md=service&cl=ELM&at=ELMReturn';
        $config = new ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $UserService = new ElemeOpenApi\OAuth\OAuthClient($config);
        $UUIDStr = $this->UUIDStr();
        $r = $UserService->get_auth_url($UUIDStr, 'all', $Rurl);
        file_put_contents('logs/OauthUrl.log', date('Y-m-d H:i:s') . '  reception：' . $r . PHP_EOL, FILE_APPEND);
        echo '<pre>';
        var_dump($r);
        die;
    }

    /******************************************************************  个人 TOKEN ******************************************************************/
    /**
     * 获取授权地址  个人
     */
    public function GR_getOauthUrlAction()
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $Tokencurl = (($webSite['debug']) ? self::ELM_SANDBOX_TOKEN_URL : self::ELM_TOKEN_URL);
        $TokenParameter['scope'] = "all";
        $TokenParameter['grant_type'] = 'client_credentials';
        $r = $this->GR_GetAccessToken($Tokencurl, $TokenParameter, $key, $secret);
        $TokenData = json_decode($r, true);
        $log = new Logging();
        $log->lfile('TokenStr');
        $log->lwrite('reception:' . $r);
//        $TokenData['t'] = time();
//        $path = 'webroot/file/token/';
//        if (!is_dir($path)) {
//            mkdir($path, 0777, true);
//        }
//        file_put_contents($path . 'TokenStr.txt', json_encode($TokenData, JSON_UNESCAPED_UNICODE));
        return $TokenData;
    }

    # POST
    function GR_GetAccessToken($url, $post_data, $key, $secret)
    {
        $Basic = base64_encode($key . ":" . $secret);
        $header_data[] = "Content-type:application/x-www-form-urlencoded";
        $header_data[] = "Authorization:Basic " . $Basic;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        $sResult = curl_exec($ch);
        $log = new Logging();
        $log->lfile('get_Token');
        $log->lwrite('send:' . $url.'');
        $log->lwrite('send:' . $url.'-'.$key.'-'.$secret.'-'.json_encode($post_data,JSON_UNESCAPED_UNICODE));
        $log->lwrite('reception:' . $sResult);
        if ($sError = curl_error($ch)) {
            die($sError);
        }
        curl_close($ch);
        return $sResult;
    }
    /******************************************************************  个人 TOKEN ******************************************************************/


    /**
     * 获取饿了么推送订单
     */
    public function ELMOrdersAction()
    {
        $cancelOrderData = file_get_contents("php://input");
        $log = new Logging();
        $log->lfile('ELMPorders');
        $log->lwrite('reception:' . $cancelOrderData);
        $orderDatas = json_decode($cancelOrderData, true);
        $orderInfo = json_decode($orderDatas['message'], true);
        $r = ['message' => 'ok'];

        $elm_shopids=$this->model->getElmShopID();
        $pass = array();
        if (!empty($elm_shopids)){
            foreach($elm_shopids as $value){
                $pass[$value['elm_shop_id']]=$value;
            }
        }
        if ($orderDatas && count((array)$orderDatas) > 0 && $orderInfo && count((array)$orderInfo) > 0 && $orderDatas['type'] == 12) {
            if(isset($pass[$orderInfo['shopId']])){
                $field['status'] = 1;
                $field['orderID'] = $orderInfo['orderId'];
                $field['shopID'] = $orderInfo['shopId'];
                $field['push_time'] = date('Y-m-d H:i:s');
                $this->model->addItem($field, 'elm');
            }
        }
        echo json_encode($r);
    }


    /**
     * 饿了么 后台 手动授权(需要登录) 回调接口必须为 https
     * 请求地址例：https://open-api-sandbox.shop.ele.me/authorize?response_type=code&client_id=qRij49iQcy&redirect_uri=https%3A%2F%2Fzhaipei.shjieta.com.cn%2F%3Fmd%3Dservice%26cl%3DELM%26at%3DELMReturn&scope=all&state=b7cbee20-9d61-4047-b6f9-1cd1983178cd
     * 参数 client_id->String->必须=应用的key，创建应用时获得
     * 参数 response_type->String->必须=code，授权类型，固定为code，表示授权码模式
     * 参数 redirect_uri->String->必须=应用的授权回调地址， redirect_uri指的是应用发起请求时，所传的回调地址参数，在用户授权后页面会跳转至redirect_uri。要求与应用注册时填写的授权回调地址一致或域名一致，并且必须支持https访问。需要进行Url Encode编码
     * 参数 scope->String->必须=all， 商户授权的权限范围，固定为all，表示所有权限
     * 参数 state->String->必须=String， 开发者自定义的应用状态，可以指定任意值，认证服务器会原样返回这个值，开发者需要确认当前授权的传入值与返回值是一致的，确保不会产生csrf漏洞。
     * 回调 获取 code
     */
    public function ELMReturnAction()
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $Rurl = (($webSite['debug']) ? self::JT_TEST_URL : self::ZP_URL) . '?md=service&cl=ELM&at=ELMReturn';
        $Tokencurl = (($webSite['debug']) ? self::ELM_SANDBOX_TOKEN_URL : self::ELM_TOKEN_URL);
        $TokenParameter['code'] = $_GET['code'];
//        $TokenParameter['grant_type'] = 'authorization_code';
        $TokenParameter['grant_type'] = 'client_credentials';
        $TokenParameter['redirect_uri'] = $Rurl;
        $TokenParameter['client_id'] = $key;
        if (!empty($TokenParameter['code'])) {
            $tr = $this->GetAccessToken($Tokencurl, $TokenParameter);
            file_put_contents('logs/getToken.log', date('Y-m-d H:i:s') . $tr . PHP_EOL);

            $TokenData = json_decode($tr, true);
            $TokenData['t'] = time();
            # 令牌有效时间，单位秒，在令牌有效期内可以重复使用。有效期限制（access_token：沙箱环境为1天、正式环境为30天，refresh_token：沙箱环境为15天、正式环境为35天）
//            $elm['store_ID'] = $TokenData['token_type'];          # 拿token 去找店铺
//            file_put_contents('logs/TokenStr.txt', json_encode($TokenData));
            file_put_contents('webroot/file/token/TokenStr.txt', json_encode($TokenData));
            echo '<pre>';
            var_dump($TokenData);
        }

    }


    /**
     * 刷新token
     * curl -i -XPOST -H "Content-Type: application/x-www-form-urlencoded"
     * -H "Authorization: Basic OU9LV2JtVXJLcjoyZGRiZTc2NTkzOWZhZjI5ZDEwNTU3MDg3MzVjOGViNw=="
     * -d "grant_type=refresh_token&refresh_token=21a5b98083e13676c5fc3948df4f0852"
     * https://open-api-sandbox.shop.ele.me/token
     */
    public function refreshTokenAction($refresh_token)
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $Tokencurl = (($webSite['debug']) ? self::ELM_SANDBOX_TOKEN_URL : self::ELM_TOKEN_URL);
        $TokenParameter['grant_type'] = 'refresh_token';
        $TokenParameter['refresh_token'] = $refresh_token;
        $tr = $this->GetAccessToken($Tokencurl, $TokenParameter);
        $TokenData = json_decode($tr, true);
        $TokenData['t'] = time();
//        file_put_contents('logs/TokenStr.txt', json_encode($TokenData));
        file_put_contents('webroot/file/token/TokenStr.txt', json_encode($TokenData));

        return $TokenData;
    }


    /**
     * 获取Token
     * @param $url
     * @param $post_data
     * @return bool|false|string
     * curl -i -XPOST -H "Content-Type: application/x-www-form-urlencoded"
     * -H "Authorization: Basic OU9LV2JtVXJLcjoyZGRiZTc2NTkzOWZhZjI5ZDEwNTU3MDg3MzVjOGViNw=="
     * -d "grant_type=authorization_code&code=f5d9280fce5cedc761f1f19ef484e7e0&redirect_uri=[redirect_uri]&client_id=9OKWbmUrKr"
     * https://open-api-sandbox.shop.ele.me/token
     */
    function GetAccessToken($url, $post_data)
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('ELMrefreshToken');
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $Basic = base64_encode($key . ":" . $secret);
        $header_data[] = "Content-type:application/x-www-form-urlencoded";
        $header_data[] = "Authorization:Basic " . $Basic;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        $sResult = curl_exec($ch);
        if ($sError = curl_error($ch)) {
            die($sError);
        }
        curl_close($ch);
        $log->lwrite('reception:' . $sResult);
        return $sResult;
    }

    /**
     * 获取饿了么订单 根据id
     * @param $K 应用的app key
     * @param $orderID 订单ID
     */
    public function getOrdersAction($orderID)
    {
//    public function getOrdersAction(){
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('ELMorder_BY_ID');
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $token = $this->refresh();

        $config = new ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $UserService = new \ElemeOpenApi\Api\OrderService($token, $config);
        $r = $UserService->get_order($orderID);
        $r = json_decode(json_encode($r), true);
        $log->lwrite('reception:' . json_encode($r, JSON_UNESCAPED_UNICODE));
        return $r;
    }

    /**
     * 排程走
     */
    public function getOrders_crontabAction()
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
		$log = new Logging();
        $log->lfile('getOrderBYCrontab');
		$log->lwrite(date('Y-m-d H:i:s'));
        /** @var 查询订单 $log */
        $t = date('H');
        if($t == 23){
            $sql_d = "delete from elm  where to_days(now())-to_days(push_time)>=3";
            $this->model->_del($sql_d);
        }
        $where = array('AND' => array('=' => array('status' => '1')));
        $info = $this->model->getItemByOther($where, 'elm');
        
        $log_o = new Logging();
        $log_o->lfile('ELMorder_BY_ID');
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $token = $this->refresh();
        if($info && count((array)$info) > 0){
            $config = new ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
            $UserService = new \ElemeOpenApi\Api\OrderService($token, $config);
            foreach ($info as $i){
                $OrderData = $UserService->get_order($i['orderID']);
                $log_o->lwrite('订单号:' . json_encode($OrderData,JSON_UNESCAPED_UNICODE));
                $Order = json_decode(json_encode($OrderData), true);
                if ($Order && count((array)$Order) > 0 && $Order['openId']) {

                    $where = array('AND' => array('=' => array('ph_no' => 'ELM'.$Order['id'], 'shop_no' => $Order['openId'], 'isdeleted' => 0)));
                    $info = $this->model->getItemByOther($where, 'orders');

                    if ($info && count((array)$info) > 0) {
                        $m = $i['orderID'].' 该订单已被添加';
                        $log->lwrite('订单号:' . $m);
                        $field = [];
                        $field['status'] = '5';
                        $where_fields = array("AND" => array("=" => array('orderID' => $i['orderID'])));
                        $this->model->updateItem($field, $where_fields, 'elm');
                        continue;
                    }
                    # 包含了外部店铺ID  如果店铺有设置外部店铺ID
                    $Store = $this->getStoresByStoreIDAction($Order['shopId']);
                    $Store = json_decode(json_encode($Store), true);
                    if ($Store && count((array)$Store) > 0) {
                        if ($Order['status'] == 'valid') {         # 接收已支付 商家已接收订单
                            $locat = explode(',', $Order['deliveryGeo']);
                            $t = $Order['consigneePhones'][0];
                            $field['order_no'] = $Order['id'];
                            $field['shop_no'] = $Order['openId'];
                            $field['lat'] = $locat[1];
                            $field['lng'] = $locat[0];
                            $field['source'] = '饿了么';
                            $field['buyer'] = $Order['consignee'];
                            $field['receiver'] = $Order['consignee'];
                            $field['receiver_tel'] = $t;
                            $field['receiver_address'] = $Order['deliveryPoiAddress'];
                            $field['customre_memo'] = $Order['description'];
                            $field['actual_pay'] = $Order['totalPrice'];
                            $field['order_time'] = str_replace('T', ' ', $Order['createdAt']);

                            if ($Order['deliverTime']) {
                                $delivery_time = str_replace('T', ' ', $Order['deliverTime']);
                            } else {
                                $delivery_time = date('Y-m-d H:i:s', strtotime('+1 hour'));
                            }
                            $field['delivery_time'] = $delivery_time;

                            $field['consignment_sync'] = 'Y';
                            $field['status'] = 0;
                            $field['shop_no'] = $Order['openId'];
                            $field['shop_name'] = $Store['name'];
                            $field['ph_no'] = 'ELM'.$Order['id'];;
                            $field['pos_fee'] = $Store['deliverFee'];

                            $distance = $this->getdistanceAction($locat[0], $locat[1], $Store['longitude'], $Store['latitude']);
                            if ($distance) {
                                $distance = round($distance, 2);
                            } else {
                                $distance = 0;
                            }
                            $field['distance'] = $distance;

                            $field['createdt'] = 'now()';
                            $OID = $this->model->addItem($field, 'orders');

                            if ($OID > 0) {
                                $field = [];
                                foreach ($Order['groups'] as $deit) {
                                    foreach ($deit['items'] as $v) {
                                        $field['orders_id'] = $OID;
                                        $field['product_no'] = $v['vfoodId'];
                                        $field['product_name'] = $v['name'];
                                        $field['qty'] = $v['quantity'];
                                        $field['unit_price'] = $v['price'];
                                        $field['ph_no'] = 'ELM' . $Order['id'];
                                        $field['createdt'] = 'now()';
                                        $this->model->addItem($field, 'orders_product');
                                    }
                                }
                                $field = [];
                                $field['status'] = '2';
                                $where_fields = array("AND" => array("=" => array('orderID' => $i['orderID'])));
                                $this->model->updateItem($field, $where_fields, 'elm');
                                $m = $i['orderID'].'添加成功';
                                $log->lwrite('订单号:' . $m);
                            }
                        }else {
                            $m = $i['orderID'].' '.$Order['status'];
                            $log->lwrite('订单号:' . $m);
                            $field = [];
                            $field['status'] = '6';
                            $where_fields = array("AND" => array("=" => array('orderID' => $i['orderID'])));
                            $this->model->updateItem($field, $where_fields, 'elm');
                            continue;
                        }
                    }else{
                        $m = $i['orderID'].' 店铺信息有误';
                        $log->lwrite('订单号:' . $m);
                        $field = [];
                        $field['status'] = '3';
                        $where_fields = array("AND" => array("=" => array('orderID' => $i['orderID'])));
                        $this->model->updateItem($field, $where_fields, 'elm');
                        continue;
                    }
                }else{
                    $m = $i['orderID'].' 该订单不存在 或 已被取消';
                    $log->lwrite('订单号:' . $m);
                    $field = [];
                    $field['status'] = '4';
                    $where_fields = array("AND" => array("=" => array('orderID' => $i['orderID'])));
                    $this->model->updateItem($field, $where_fields, 'elm');
                    continue;
                }
            }
        }else{
            $m = '没有更多订单';
            $log->lwrite('订单号:' . $m);
        }

    }


    /**
     * 获取门店ID 通过token 可获取所有店铺信息
     */
    public function getStoresAction()
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('ELMorder_token_log');
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $token = $this->refresh();
        $config = new ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $log->lwrite('info=> key:' . $key.', secret:'.$secret.', debug:'.$webSite['debug'].', token:'.$token.', config:'.json_encode($config,JSON_UNESCAPED_UNICODE));
        $UserService = new ElemeOpenApi\Api\UserService($token, $config);
        $r = $UserService->get_user();
        $log->lwrite('reception:' . json_encode($r, JSON_UNESCAPED_UNICODE));
        $r = json_decode(json_encode($r), true);
        var_dump($r);
    }


    /**
     * 获取门店信息 通过店铺ID
     */
    public function getStoresByStoreIDAction($storeID){
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('ELMgetStoresByStoreID');
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $token = $this->refresh();
        $config = new \ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $ShopService = new \ElemeOpenApi\Api\ShopService($token, $config);
        $log->lwrite('info=> key:' . $key.', secret:'.$secret.', debug:'.$webSite['debug'].', token:'.$token.', storeid:'.$storeID.', config:'.json_encode($config,JSON_UNESCAPED_UNICODE));
        $r = $ShopService->get_shop($storeID);
        $r = json_decode(json_encode($r), true);
        $log->lwrite('reception:' . json_encode($r, JSON_UNESCAPED_UNICODE));
        return $r;

    }


    /**
     * 绑定店铺
     */
    public function BindStoreAction(){
        require_once('plugin/PHPExcelNew/Classes/PHPExcel/IOFactory.php');
        //加载excel文件
        $filename = 'webroot/file/elm_excel/elm.xlsx';  # excel 文件
        $objPHPExcelReader = PHPExcel_IOFactory::load($filename);

        $reader = $objPHPExcelReader->getWorksheetIterator();
        //循环读取sheet
        foreach($reader as $sheet) {
            //读取表内容
            $content = $sheet->getRowIterator();
            //逐行处理
            $res_arr = array();
            foreach($content as $key => $items) {

                $rows = $items->getRowIndex();              //行
                $columns = $items->getCellIterator();       //列
                $row_arr = array();
                //确定从哪一行开始读取
                if($rows < 2){
                    continue;
                }
                //逐列读取
                foreach($columns as $head => $cell) {
                    //获取cell中数据
                    $data = $cell->getValue();
                    $row_arr[] = $data;
                }

                $res_arr[] = $row_arr;
            }

        }

        # 绑定
        if($res_arr && count((array)$res_arr) > 0 ){
            foreach ($res_arr as $k=>$r){
//                if($k==0){
//                    var_dump($r);
//                    $this->updateStoreAction($r[1],$r[0]);
//                    break;
//                }
                $this->updateStoreAction($r[1],$r[0]);
                echo $k.': store_id:'.$r[1].', elmid:'.$r[0].'<br/>';
            }
        }
    }


    /**
     * 修改店铺 绑定第三方店铺
     */
    public function updateStoreAction($zp_shop_id,$elm_shop_id)
    {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('ELMupdateStore');
        $log->lwrite('店铺信息 info:' . 'zp:'.$zp_shop_id.'----'.'elm'.$elm_shop_id);

        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $token = $this->refresh();
        $log->lwrite('token:'.$token);
        $shopID = $elm_shop_id; # elm
        $properties = [];
//        $properties["addressText"] = "上海市长宁区龙溪路虹桥路1923号";
//        $properties["geo"] = "121.223,31.233";
//        $properties["agentFee"] = 3.0;
//        $properties["closeDescription"] = "正常营业";
//        $properties["deliverDescription"] = "超过5公里，100元起送";
//        $properties["deliverGeoJson"] = '{"type":"FeatureCollection","features":[{"geometry":{"type":"Polygon","coordinates":[[[121.381303,31.243521],[121.380938,31.242778],[121.381679,31.243297],[121.381303,31.243521]]]},"type":"Feature","properties":{"area_agent_fee":20,"delivery_price":10,"manual_weight":0,"system_weight":0,"weight_type\":1}}]}';
//        $properties["description"] = "便宜好吃的小食";
//        $properties["name"] = "烤鸭大王";
//        $properties["isBookable"] = 1;
//        $properties["openTime"] = "10:00-13:00,18:00-21:00";
//        $properties["phone"] = "13666666666";
//        $properties["logoImageHash"] = "13666666666";
//        $properties["promotionInfo"] = "本周全场半价";
//        $properties["invoice"] = 1;
//        $properties["invoiceMinAmount"] = 100.0;
//        $properties["noAgentFeeTotal"] = 20.0;
//        $properties["isOpen"] = 1;
//        $properties["packingFee"] = 2.0;
        $properties["openId"] = "$zp_shop_id";

        $config = new ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $ShopService = new \ElemeOpenApi\Api\ShopService($token, $config);
        $r = $ShopService->update_shop($shopID, $properties);
        $log->lwrite('reception:' . json_encode($r, JSON_UNESCAPED_UNICODE));
        if (!isset($r->error)) {
            $field = array();
            $field['elm_shop_id'] = $elm_shop_id;
            $where_fields = array("AND" => array("=" => array('store_id' => $zp_shop_id)));
            $this->model->updateItem($field, $where_fields, 'xd_store');
        }
    }


    /**
     * 手动绑定指定门店测试下单
     */
    public function updateStore_tempAction()
    {
        $zp_shop_id = '';
        $elm_shop_id = '';
        if(isset($this->params["elm_shop_id"]) && isset($this->params["shop_id"])) {
            $zp_shop_id = $this->params["shop_id"];
            $elm_shop_id = $this->params["elm_shop_id"];
        }
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('manual_update');
        $log->lwrite('店铺信息 info:' . 'zp:'.$zp_shop_id.'----'.'elm'.$elm_shop_id);

        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $properties = [];
        if(isset($this->params["t"]) && $this->params['t'] == 'unbind'){
            $properties["openId"] = "";
            $msg = '解绑成功';
            $tmp_elm_shop_id = '';
        }else{
            $where = array('AND' => array('=' => array('elm_shop_id'=>$elm_shop_id)));
            $store = $this->model->getItemByOther($where, 'xd_store');
            if($store && count($store) > 0){
                echo json_encode(['status'=>0,'msg'=>'该饿了么店铺已被其他门店绑定']);
                exit;
            }
            $properties["openId"] = "$zp_shop_id";
            $msg = '绑定成功';
            $tmp_elm_shop_id = $elm_shop_id;
        }
        $token = $this->refresh();
        $config = new ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $ShopService = new \ElemeOpenApi\Api\ShopService($token, $config);
        $r = $ShopService->update_shop((int)$elm_shop_id, $properties);
        $log->lwrite('reception:' . json_encode($r, JSON_UNESCAPED_UNICODE));

        if(!isset($r->error)){
            $field = array();
            $field['elm_shop_id'] = $tmp_elm_shop_id;
            $field['elm_result'] = json_encode($r,JSON_UNESCAPED_UNICODE);
            $where_fields = array("AND" => array("=" => array('store_id' => $zp_shop_id)));
            $this->model->updateItem($field, $where_fields, 'xd_store');
            echo json_encode(['status'=>200,'msg'=>$msg]);
        }else{
            echo json_encode(['status'=>0,'msg'=>$r->error->message]);
        }
    }


    /**
     * 手动获取店铺信息
     */
    public function getStoresByStoreID_tempAction() {
        $storeID = 2035016581;
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('ELMgetStoresByStoreID_temp');
        $secret = (($webSite['debug']) ? self::SANDBOX_SECRET : self::SECRET);
        $key = (($webSite['debug']) ? self::SANDBOX_KEY : self::KEY);
        $token = $this->refresh();

        $config = new \ElemeOpenApi\Config\ELMConfig($key, $secret, $webSite['debug']);
        $ShopService = new \ElemeOpenApi\Api\ShopService($token, $config);
        $r = $ShopService->get_shop($storeID);
        $r = json_decode(json_encode($r), true);
        $log->lwrite('reception:' . json_encode($r, JSON_UNESCAPED_UNICODE));
        var_dump($r);
    }

    /**
     * 计算是否过期
     * @return mixed    新token
     */

    private function refresh()
    {
//        $str = file_get_contents('webroot/file/token/TokenStr.txt');
//        $str = json_decode($str, true);
//        $token = $str['access_token'];
//        $ntime = time();
//        $otime = $str['t'];
//        $expires_in = $str['expires_in'];
//        $otime = $otime + ($expires_in - 1800);    # 生成时间 提前半小时
//        if ($ntime >= $otime) {
//            $TokenData = $this->GR_getOauthUrlAction();
//            $token = $TokenData['access_token'];
//        }
//        return $token;

        $token = $this->model->getToken();

        if (is_array($token) && count((array)$token) > 0){
            $row = $token;
            $expires_in = $row['expires_in'] - 60;
            $createdt = $row['createdt'];
            $token_time = strtotime(date('Y-m-d H:i:s', strtotime('+ ' . $expires_in . ' seconds', strtotime($createdt))));
            $now = strtotime(date('Y-m-d H:i:s'));

            if ($now > $token_time) {
                $token_result = $this->GR_getOauthUrlAction();
                if (is_array($token_result) && count($token_result) > 0) {
                    $field_update = array();
                    $field_update['access_token'] = $token_result['access_token'];
                    $field_update['expires_in'] = $token_result['expires_in'];
                    $field_update['createdt'] = date('Y-m-d H:i:s');
                    $where_fields = array("AND" => array("=" => array('type' => 'access_token')));
                    $this->model->updateItem($field_update, $where_fields, 'access_token');
                    return $token_result['access_token'];
                }
            } else {
                return $row['access_token'];  //DB access_token
            }

        } else {
            $token_result = $this->GR_getOauthUrlAction();
            $field_update = array();
            $field_update['type'] = 'access_token';
            $field_update['access_token'] = $token_result['access_token'];
            $field_update['expires_in'] = $token_result['expires_in'];
            $field_update['createdt'] = date('Y-m-d H:i:s');
            $r = $this->model->addItem($field_update, 'access_token');

            if($r){
                return $token_result['access_token'];
            }else{
                return '';
            }
        }

    }


    /**
     * POST 请求 API
     * @param $url
     * @param $post_data
     * @return bool|string
     */
    function http_post($url, $post_data)
    {
        $header_data[] = "application/json;charset=utf-8";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        $sResult = curl_exec($ch);
        $info = curl_getinfo($ch);
        if ($sError = curl_error($ch)) {
            die($sError);
        }
        curl_close($ch);
        print_r($info);
        return $sResult;
    }


    /**
     * @return string 随机字符串
     */
    private function UUIDStr()
    {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    private function getdistanceAction($lng1, $lat1, $lng2, $lat2)
    {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }
}